import { asyncRoutes, constantRoutes } from '@/router'

/**
 * Use meta.role to determine if the current user has permission
 * @param roles
 * @param route
 */
function hasPermission( roles, route ) 
{
    return true;
    return roles.some( role => route.redirect == role || route.path == role );
}

/**
 * Filter asynchronous routing tables by recursion
 * @param routes asyncRoutes
 * @param roles
 */
export function filterAsyncRoutes( routes, roles, root_path = null, parent_path = null, is_top = true ) {
    const res = [];
    routes.forEach( route => {
        const tmp = { ...route };
        //root_path
        if( ! root_path && routes.length > 0 )
        {
            root_path = route.path;
        }

        //parent_path
        if( ! parent_path )
        {
            parent_path = route.path;
        }
        
        if ( hasPermission( roles, tmp ) ) 
        {
            if ( tmp.children ) 
            {
                tmp.children = filterAsyncRoutes( tmp.children, roles, root_path, route.path, false );
            }

            //meta
            if( ! tmp.meta )
            {
                tmp.meta = {};
            }

            //root path
            tmp.meta.root_path = root_path;

            //parent path
            tmp.meta.parent_path = parent_path;

            if( is_top )
            {
                root_path = null;   //初始化root path
                parent_path = null;   //初始化parent path
            }

            res.push( tmp )
        }
    } )
    return res
}

const state = {
    routes: [],
    addRoutes: []
}

const mutations = {
    SET_ROUTES: ( state, routes ) => {
        state.addRoutes = routes
        state.routes = constantRoutes.concat( routes )
    }
}

const actions = {
    generateRoutes( { commit }, roles ) {
        return new Promise( resolve => {
            const accessedRoutes = filterAsyncRoutes( asyncRoutes, roles );
            commit( 'SET_ROUTES', accessedRoutes )
            resolve( accessedRoutes )
        } )
    }
}

export default {
    namespaced: true,
    state,
    mutations,
    actions
}
